package com.ipan.jfinal.plugin.activerecord;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.ipan.jfinal.annotation.Crypto;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.builder.TimestampProcessedRecordBuilder;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;

/**
 * OracleDialect加密解密方言
 * 
 * @author iPan
 * @date 2021-12-07
 */
public class MyOracleDialect extends OracleDialect {

	private MyCryptoHandler handler = null;
	
	public MyOracleDialect() {
		super();
	}
	public MyOracleDialect(MyCryptoHandler h) {
		this.modelBuilder = new MyModelBuilder(h);
		this.recordBuilder = TimestampProcessedRecordBuilder.me;
		this.handler = h;
	}
	
	public MyCryptoHandler getHandler() {
		return handler;
	}

	public void setHandler(MyCryptoHandler handler) {
		this.handler = handler;
	}

	private String encrypt(Crypto crypto, String colName, String value) {
		if (crypto == null) return value;
		String[] values = crypto.value();
		if (values == null || values.length < 1) {
			return value;
		}
		
		// 检测是否加密
		for (String attName : values) {
			if (colName.equals(attName)) {
				return handler.encrypt(value); // 加密
			}
		}
		// 不用加密
		return value;
	}
	
	// insert into table (id,name) values(seq.nextval, ？)
	public void forModelSave(Table table, Map<String, Object> attrs, StringBuilder sql, List<Object> paras) {
		Crypto crypto = table.getModelClass().getAnnotation(Crypto.class);
		sql.append("insert into ").append(table.getName()).append('(');
		StringBuilder temp = new StringBuilder(") values(");
		String[] pKeys = table.getPrimaryKey();
		int count = 0;
		for (Entry<String, Object> e: attrs.entrySet()) {
			String colName = e.getKey();
			if (table.hasColumnLabel(colName)) {
				if (count++ > 0) {
					sql.append(", ");
					temp.append(", ");
				}
				sql.append(colName);
				Object value = e.getValue();
				if (value instanceof String && isPrimaryKey(colName, pKeys) && ((String)value).endsWith(".nextval")) {
				    temp.append(value);
				} else {
				    temp.append('?');
					// crypto为空直接返回，提高效率；
					paras.add((crypto == null || !(value instanceof String)) ? value : encrypt(crypto, colName, (String)value));
				}
			}
		}
		sql.append(temp.toString()).append(')');
	}
	
	public void forModelUpdate(Table table, Map<String, Object> attrs, Set<String> modifyFlag, StringBuilder sql, List<Object> paras) {
		Crypto crypto = table.getModelClass().getAnnotation(Crypto.class);
		sql.append("update ").append(table.getName()).append(" set ");
		String[] pKeys = table.getPrimaryKey();
		for (Entry<String, Object> e : attrs.entrySet()) {
			String colName = e.getKey();
			if (modifyFlag.contains(colName) && !isPrimaryKey(colName, pKeys) && table.hasColumnLabel(colName)) {
				if (paras.size() > 0) {
					sql.append(", ");
				}
				sql.append(colName).append(" = ? ");
				Object value = e.getValue();
				// crypto为空直接返回，提高效率；
				paras.add((crypto == null || !(value instanceof String)) ? value : encrypt(crypto, colName, (String)value));
			}
		}
		sql.append(" where ");
		for (int i=0; i<pKeys.length; i++) {
			if (i > 0) {
				sql.append(" and ");
			}
			sql.append(pKeys[i]).append(" = ?");
			paras.add(attrs.get(pKeys[i]));
		}
	}
	
}
